import threading
import queue
from queue import Queue
import asyncio
from typing import List, Tuple
from queue import Queue
import struct
import binascii

# 用于存储接收到的数据的缓冲区
m0_data = None
cat1_data = None
sended_len = -1
pack_len = 0
recv_ack = False
wait_cat1_img_trans = 0 #等待一段时间，让m0先把cat1数据传输给cat1
# 线程停止标志
ota_thread_stop = threading.Event()


def GetChecksum(data: bytearray) -> int:
    ret = 0
    for i in range(len(data)):
        ret = (ret + (data[i] << ((i % 4) * 8)) & 0xffffffff)
    return (-ret & 0xffffffff)

def pack_ota_data(cmd:int, data) -> bytes:
    # pack
    # 1. 构建初始数据包（校验和位置用0填充）
    packet = bytearray(8)+data
    packet[0] = 0xAA            # 起始字节 0xAA
    packet[1] = cmd             # 命令字节
    # 2. 计算总长度并填充到指定位置
    total_length = len(packet)
    packet[2] = total_length & 0xFF
    packet[3] = (total_length >> 8) & 0xFF
    # 3. 计算整个数据包的逐字节求和校验和
    # (校验和位置在计算时视为0)
    checksum = GetChecksum(packet)
    # 将校验和以小端格式填充回数据包
    packet[4] = checksum & 0xFF           # 最低有效字节
    packet[5] = (checksum >> 8) & 0xFF
    packet[6] = (checksum >> 16) & 0xFF
    packet[7] = (checksum >> 24) & 0xFF   # 最高有效字节
    return bytes(packet)

